import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;

public class pay {
    private static final String BASE_URL = "http://121.36.106.217:9005/";
    private static String TOKEN = null;
    private static final String MCHID = "20170100";
    private static final String APPID = "20221120242";
    private static final OkHttpClient client = new OkHttpClient();

    // 付款
    public void pay(double amount, PaymentCallback callback) {
        Client client1 = new Client();
        String TOKEN = null;
        try {
            TOKEN = client1.isAvailable();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        String url = BASE_URL + "wechat/transaction/pay"; // 微信付款接口
//        String url = BASE_URL + "alipay/transaction/pay"; //
        // 付款接口根据支付方式（微信/支付宝）选择不同的URL
        // 此代码以微信为例，支付宝类似处理

        RequestBody formBody = new FormBody.Builder()
                .add("mchid", MCHID)
                .add("appid", APPID)
                .add("amount", String.valueOf(amount))
                .add("token", TOKEN)
                .add("content", "content")
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();

        OkHttpClient client = new OkHttpClient();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 请求失败时的处理
                callback.onPaymentFailure(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 解析响应内容
                    String responseBody = response.body().string();
                    System.out.println("支付应答: " + responseBody);
                    try {
                        JSONObject jsonObject = new JSONObject(responseBody);
                        JSONObject dataObject = jsonObject.getJSONObject("data");
                        String orderId = dataObject.getString("orderid");
                        callback.onPaymentSuccess(orderId);
                    } catch (JSONException e) {
                        callback.onPaymentFailure("Payment failed with code: " + response.code());
                    }
                } else {
                    System.out.println("Payment failed with code: " + response.code());
                }
            }
        });
    }
}
